package com.takeshequ.conversation;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.takeshequ.Constants;
import com.takeshequ.R;
import com.takeshequ.SMApplication;
import com.takeshequ.chat.ExpressionUtil;
import com.takeshequ.chat.TalkActivity;
import com.takeshequ.chat.TalkHistory;
import com.takeshequ.friends.AddressBookContactsActivity;
import com.takeshequ.friends.BaseData;
import com.takeshequ.friends.Friend;
import com.takeshequ.main.BasicFragment;
import com.takeshequ.main.MainFragmentActivity;
import com.utils.SharedPreferencesUtils;

public class ConversationFragment extends BasicFragment implements
		AdapterView.OnItemClickListener {
	static Context context = null;
	private static SMApplication application;
	private static SimpleDateFormat sf = new SimpleDateFormat(
			"yyyy年MM月dd日  HH:mm:ss");
	private static SimpleDateFormat sf2 = new SimpleDateFormat("HH:mm");
	private Map<Integer, View> viewMap = new HashMap<Integer, View>();
	private List<UnRead> unReadList = new ArrayList<UnRead>();

	public static ConversationFragment newInstance(Context con,
			SMApplication app) {
		context = con;
		application = app;
		ConversationFragment newFragment = new ConversationFragment();
		return newFragment;

	}

	private static ArrayList<ConversationListItem> items;
	static {
		items = new ArrayList<ConversationListItem>();
	}

	private ListView listView;
	private ItemAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void getListItems() throws ParseException {

		items.clear();
		FinalDb finalDb = FinalDb.create(context);
		List<TalkHistory> talkHistoryTempList = finalDb.findAllByWhere(
				TalkHistory.class, " 1=1  group by talkGroupId");
		for (TalkHistory talkHistory : talkHistoryTempList) {
			if (talkHistory.getTalkGroupId() != null) {
				String targetId = talkHistory.getTalkGroupId().split(",")[1];
				if (BaseData.getFriend(targetId) instanceof Friend) {
					ConversationListItem conversationItem = new ConversationListItem();
					conversationItem.setHeadImg(BaseData.getFriend(targetId)
							.getHeadImage());
					conversationItem.setLastTime(sf2.format(sf
							.parse(talkHistory.getDate())));
					conversationItem
							.setNickName(BaseData.getNickName(targetId));
					conversationItem.setMemberId(targetId);
					conversationItem.setLastContent(talkHistory.getContent());
					items.add(conversationItem);
				}

			}

		}

	}

	@Override
	public void onResume() {
		super.onResume();
		show();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.conversation, container, false);
		listView = (ListView) view.findViewById(R.id.conversation_listview);
		adapter = new ItemAdapter(inflater);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		ConversationListItem item = items.get(i);
		if (item.getType().equals("1")) {
			Constants.firend = BaseData.getFriend(item.getMemberId());
			Intent intent = new Intent(context, TalkActivity.class);
			startActivity(intent);
		}else if(item.getType().equals("2")){
			Intent intent = new Intent(context,DealWithAddFriendActivity.class);
			intent.putExtra("mid", item.getMid());
			intent.putExtra("text",item.getLastContent());
			startActivity(intent);
		}
	}

	class ItemAdapter extends BaseAdapter {

		private LayoutInflater inflater;

		private class ViewHolder {
			public TextView nickName, content, date;
			public ImageView headImage;
		}

		public ItemAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (items.size() > position) {
				View view = viewMap.get(position);
				ConversationListItem conversationItem = items.get(position);
				final ViewHolder holder;
				if (view == null) {
					view = inflater.inflate(R.layout.conversation_list_item,
							parent, false);
					holder = new ViewHolder();
					holder.nickName = (TextView) view
							.findViewById(R.id.conversation_list_view_nickName);
					holder.date = (TextView) view
							.findViewById(R.id.conversation_list_view_last_time);
					holder.content = (TextView) view
							.findViewById(R.id.conversation_list_view_last_content);
					holder.headImage = (ImageView) view
							.findViewById(R.id.conversation_list_view_headImg);
					view.setTag(holder);
					viewMap.put(position, view);
				} else {
					holder = (ViewHolder) view.getTag();
				}

				FinalBitmap.create(context).display(holder.headImage,
						conversationItem.getHeadImg());
				holder.nickName.setText(conversationItem.getNickName());
				holder.date.setText(conversationItem.getLastTime());
				String content = conversationItem.getLastContent();
				SpannableString spannableString = ExpressionUtil
						.getExpressionString(context, content);
				holder.content.setText(spannableString);
				return view;
			}
			return null;
		}
	}

	@Override
	public void show() {
		try {
			getListItems();
			adapter.notifyDataSetChanged();
			getUnReadList();
		} catch (Exception e) {
			System.err.println(e);
		}
	}

	class UnRead {
		private String fromMemberId;
		private String messageCont;
		private String toMemberId;
		private String sendDateString;
		private String fromMemberHeadImage;
		private String fromMemberNickName;
		private String messageType;
		private String actionType;
		private String mid;
		private String isDeal;

		public String getMid() {
			return mid;
		}

		public void setMid(String mid) {
			this.mid = mid;
		}

		public String getFromMemberId() {
			return fromMemberId;
		}

		public void setFromMemberId(String fromMemberId) {
			this.fromMemberId = fromMemberId;
		}

		public String getMessageCont() {
			return messageCont;
		}

		public void setMessageCont(String messageCont) {
			this.messageCont = messageCont;
		}

		public String getToMemberId() {
			return toMemberId;
		}

		public void setToMemberId(String toMemberId) {
			this.toMemberId = toMemberId;
		}

		public String getSendDateString() {
			return sendDateString;
		}

		public void setSendDateString(String sendDateString) {
			this.sendDateString = sendDateString;
		}

		public String getFromMemberHeadImage() {
			return fromMemberHeadImage;
		}

		public void setFromMemberHeadImage(String fromMemberHeadImage) {
			this.fromMemberHeadImage = fromMemberHeadImage;
		}

		public String getFromMemberNickName() {
			return fromMemberNickName;
		}

		public void setFromMemberNickName(String fromMemberNickName) {
			this.fromMemberNickName = fromMemberNickName;
		}

		public String getMessageType() {
			return messageType;
		}

		public void setMessageType(String messageType) {
			this.messageType = messageType;
		}

		public String getActionType() {
			return actionType;
		}

		public void setActionType(String actionType) {
			this.actionType = actionType;
		}

		public String getIsDeal() {
			return isDeal;
		}

		public void setIsDeal(String isDeal) {
			this.isDeal = isDeal;
		}

	}

	private void getUnReadList() {
		AsyncHttpClient client = new AsyncHttpClient();
		Map<String, String> params = new HashMap<String, String>();
		params.put("memberId", Constants.memberId);
		params.put("messageType", "");
		params.put("isRead", "0");
		params.put("type", "2");
		params.put("pageNumber", "1");
		client.get(Constants.domainAndPort + "/listMessageList",
				new RequestParams(params), new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String response) {
						try {
							System.out.println(response);
							JSONObject jsonObject = new JSONObject(response);
							Gson gson = new Gson();
							unReadList = gson.fromJson(
									jsonObject.getJSONObject("pageInfo")
											.getString("result"),
									new TypeToken<List<UnRead>>() {
									}.getType());
							for (UnRead unRead : unReadList) {
								ConversationListItem conversationItem = new ConversationListItem();
								conversationItem.setNickName(unRead
										.getFromMemberNickName());
								conversationItem.setMemberId(unRead
										.getFromMemberId());
								conversationItem.setMid(unRead.getMid());
								if (unRead.getActionType().compareTo("0") > 0
										&& unRead.getIsDeal().equals("0")) {
									conversationItem.setType("2");// 系统好友请求消息
								} else {
									conversationItem.setType("3");// 仅阅读消息
								}
								conversationItem.setLastTime(unRead
										.getSendDateString());
								conversationItem.setLastContent(unRead
										.getMessageCont());
								conversationItem
										.setHeadImg(unRead.fromMemberHeadImage);
								items.add(conversationItem);
							}
							System.out.println(items.size());
							adapter.notifyDataSetChanged();
							// System.out.println(response);
							// System.out.println(unReadList.size());
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	
}